#include "EPSG/Billboard.h"

/* EPSG Includes */
#include "EPSG/Cube.h"
#include "EPSG/Material.h"
#include "EPSG/Appearance.h"

/* System Includes */
#ifdef WIN32
	#include <Windows.h>
#endif

/* OpenGL Includes */
#include <GL/GL.h>

EPSG::Billboard::Billboard()
{
	_polygonOffset = false;
	_appearance = NULL;
	_shape = new Cube( 25, 25, 0.5f );
}

EPSG::Billboard::Billboard( EPSG::Appearance* appearance, float width, float height )
{
	_polygonOffset = false;
	setAppearance( appearance );
	_shape = new Cube( width, height, 0.1f );
}

void EPSG::Billboard::render()
{
	if( _appearance == NULL )
		_appearance = new EPSG::Material();

	if( _polygonOffset == true )
	{
		glPushAttrib( GL_POLYGON_BIT );
		glEnable( GL_POLYGON_OFFSET_FILL );

		glPolygonMode( GL_FRONT, GL_FILL );
		glPolygonOffset( _factor, _units );
	}

	float modelview[16];
	int i,j;

	glPushMatrix();
	glGetFloatv( GL_MODELVIEW_MATRIX , modelview );
	for( i=0; i<3; i++ )
	{
		for( j = 0; j < 3; j++ )
		{
			if( i == j )
				modelview[i*4+j] = 1.0;
			else
				modelview[i*4+j] = 0.0;
		}
	}
	glLoadMatrixf( modelview );

	bool hasTexCoords = _appearance->load();
	_shape->draw( !hasTexCoords );
	_appearance->unload();

	glPopMatrix();

	if( _polygonOffset == true )
	{
		glPopAttrib();
		glDisable( GL_POLYGON_OFFSET_FILL );
	}
}

void EPSG::Billboard::setDimensions( float width, float height )
{
	_shape->setDimensions( width, height, 0.1f );
}

void EPSG::Billboard::setAppearance( EPSG::Appearance* a )
{
	_appearance = a;
}

EPSG::Appearance* EPSG::Billboard::getAppearance()
{
	return _appearance;
}

void EPSG::Billboard::setPolygonOffset( float factor, float units )
{
	_factor = factor;
	_units = units;
	_polygonOffset = true;
}